package com.zmn.oms.dubbo.impl.zmn.serviceprovider.order;

import org.apache.dubbo.config.annotation.Service;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.ResponseDTO;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.response.ResponseUtil;
import com.zmn.common.utils.validator.ValidateResult;
import com.zmn.common.utils.validator.ValidatorUtil;
import com.zmn.oms.common.constant.OrderGateTypeConsts;
import com.zmn.oms.dubbo.dto.zmn.order.OrderListPageDRO;
import com.zmn.oms.dubbo.dto.zmn.order.serviceprovider.OrderQueryDIO;
import com.zmn.oms.dubbo.dto.zmn.order.serviceprovider.SpOrderDetailDRO;
import com.zmn.oms.dubbo.impl.zmn.order.OrderBaseRemoteService;
import com.zmn.oms.dubbo.interfaces.zmn.serviceprovider.order.OrderListRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.entity.log.OrderLog;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.model.vo.work.detail.ZsOrderWorkCommissionVO;
import com.zmn.oms.model.vo.work.detail.ZsOrderWorkDetailVO;
import com.zmn.oms.zmn.aop.SpOrderLogUtils;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkScheduleBService;
import io.shardingsphere.api.HintManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 类描述：服务商  订单列表详情
 *
 * @author yule
 * @date 2019/05/15 18:05
 */
@Deprecated
@Service(loadbalance = "roundrobin", timeout = 5000, retries = 2, version = DubboConsts.INTERFACE_VERSION, validation = "false")
public class OrderListRemoteServiceImpl extends OrderBaseRemoteService implements OrderListRemoteService {
	static final String TAG = "服务商-订单";
	private static final Logger logger = LoggerFactory.getLogger(OrderListRemoteServiceImpl.class);
	@Autowired
	ZsOrderWorkScheduleBService zsOrderWorkScheduleBService;

	@Override
	public ResponseDTO<OrderListPageDRO> listOrder(OrderQueryDIO orderListQueryDIO) {

		logger.info("[{}] 服务商订单列表：{}", TAG, orderListQueryDIO);

		ValidateResult validateResult = ValidatorUtil.validator(orderListQueryDIO);

		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return ResponseUtil.responseFail("提交参数错误：" + validateResult.toString());
		}

		Objects.requireNonNull(orderListQueryDIO.getCompanyId());

		OrderWorkQuery query = BeanMapper.map(orderListQueryDIO, OrderWorkQuery.class);
		query.setManageCompanyIdList(orderListQueryDIO.getCompanyId());
		query.setCompanyIdList(null);
		query.setCompanyId(null);
		if (orderListQueryDIO.getMerPartsType() != null) {
			query.setExistPartSrc(orderListQueryDIO.getMerPartsType());
		}

		query.setDefaultOrder(GlobalConsts.YES);
		query.setOrderField("receiveTime");
		query.setExistAssignConfirmTime(GlobalConsts.YES);
		return super.listOrder(query);
	}

	/**
	 * 获取默认预约时间
	 *
	 * @return
	 */
	@Override
	public ResponseDTO getDefaultDutyTime(Integer plat, Integer gateType) {
		try {
			String dutyTime = zsOrderWorkScheduleBService.getDefaultDutyTime(plat, gateType);
			return ResponseUtil.responseSuccess(dutyTime, "OK");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("[{}] 获取默认预约时间错误：{}", TAG, e);
			return ResponseUtil.responseFail(e.getMessage());
		}
	}

	@Override
	public ResponseDTO<String> processScheduleTimes(Long orderId, Integer plat, Integer gateType, String times) {
		try {
			String newTimes = zsOrderWorkScheduleBService.processScheduleTimes(orderId, plat, gateType, times);
			return ResponseUtil.responseSuccess(newTimes, "OK");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("[{}] 获取默认预约时间错误：{}", TAG, e);
			return ResponseUtil.responseFail(e.getMessage());
		}
	}

	@Override
	public ResponseDTO<SpOrderDetailDRO> findOrderWorkDetail(Long orderId, Long workId) {

		logger.info("[{}] 服务商订单详情：{}", TAG, "orderId:" + orderId + "workId:" + workId);

		Objects.requireNonNull(orderId);

		SpOrderDetailDRO orderDetailDRO = new SpOrderDetailDRO();

		try (HintManager hintManager = HintManager.getInstance()) {
			hintManager.setMasterRouteOnly();
			ZsOrderWorkDetailVO orderWorkDetail = orderWorkQueryBService.findOrderWorkDetail(orderId, workId);

			if (orderWorkDetail != null) {
				List<OrderLog> orderLogList = orderWorkDetail.getLogList();
				if (!CollectionUtils.isEmpty(orderLogList)) {
					List<OrderLog> neworderLogList;
					if (Objects.equals(GlobalConsts.PLAT_MARK_SAAS, orderWorkDetail.getPlatWork())) {
						//Saas平台服务商操作日志过滤
						neworderLogList = orderLogList.stream().filter(e -> SpOrderLogUtils.SP_SAAS_ORDER_LOG_TYPE_LIST.contains(e.getType())).collect(Collectors.toList());
					} else {
						//过滤言而有信服务商操作日志
						neworderLogList = orderLogList.stream().filter(e -> SpOrderLogUtils.YEYX_SP_ORDER_LOG_TYPE_LIST.contains(e.getType())).collect(Collectors.toList());
					}
					orderWorkDetail.setLogList(neworderLogList);
				}
			}

			BeanMapper.copy(orderWorkDetail, orderDetailDRO);
			orderDetailDRO.setWorkId(orderId);
			orderDetailDRO.setOrderId(orderId);

			if (orderWorkDetail.getCommission() != null) {
				ZsOrderWorkCommissionVO commissionVO = orderWorkDetail.getCommission();
				Integer commissionAmount = this.getCommissionAmount(commissionVO);
				orderDetailDRO.getCommission().setServiceProviderAmount(commissionAmount);
			}
		}
		return ResponseUtil.responseSuccess(orderDetailDRO, GlobalConsts.SUCCESS_MSG);
	}

	private Integer getCommissionAmount(ZsOrderWorkCommissionVO acountVO) {
		//计算提成金额
//		Integer commissionAmount = Optional.ofNullable(acountVO.getServiceProviderRetention()).orElse(0)
//				- Optional.ofNullable(acountVO.getInsurance()).orElse(0)
//				- Optional.ofNullable(acountVO.getHelpEach()).orElse(0)
//				- Optional.ofNullable(acountVO.getDeposit()).orElse(0)
//				- Optional.ofNullable(acountVO.getVoucherShare()).orElse(0)
//				- Optional.ofNullable(acountVO.getDiscountShare()).orElse(0)
//				- Optional.ofNullable(acountVO.getIntegralShare()).orElse(0);
		return acountVO.getSpReserveAmount();
	}

}
